package com.winit.schedule.task.tracker.quartz;

import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.listeners.SchedulerListenerSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.winit.schedule.core.repository.constants.QuartzManagerType;
import com.winit.schedule.core.repository.entity.QuartzLogEntity;
import com.winit.schedule.task.tracker.TaskTracker;
import com.winit.schedule.task.tracker.conf.TaskConfiguration;
import com.winit.schedule.task.tracker.quartz.event.QuartzManagerEvent;
import com.winit.schedule.task.tracker.utils.ExceptionUtils;

public class QuartzScheduleListener extends SchedulerListenerSupport {

    private static Logger logger = LoggerFactory.getLogger(QuartzScheduleListener.class);

    private TaskTracker   taskTracker;

    private Scheduler     scheduler;

    public QuartzScheduleListener(TaskTracker taskTracker, Scheduler scheduler){
        this.taskTracker = taskTracker;
        this.scheduler = scheduler;
    }

    @SuppressWarnings("unchecked")
    @Override
    public void schedulerError(String msg, SchedulerException cause) {
        if (isTaskTrackerStarted()) {
            QuartzLogEntity logEntity = new QuartzLogEntity();
            logEntity.setTaskTrackerUuid(taskTracker.getUuid());
            try {
                logEntity.setSchedulerInstanceId(scheduler.getSchedulerInstanceId());
                logEntity.setTaskGroup(taskTracker.getConfig().getString(TaskConfiguration.JT_TASK_GROUP,
            TaskConfiguration.DEFAULT_JT_TASK_GROUP));
                logEntity.setMessage(msg);
                logEntity.setCause(ExceptionUtils.getStackTrace(cause));
                taskTracker.getDispatcher()
                    .getEventHandler()
                    .handle(new QuartzManagerEvent(QuartzManagerType.SCHEDULER_EXCEPTION, logEntity));
            } catch (SchedulerException e) {
                logger.error("getSchedulerInstanceId failed.", e);
            }
        }
    }

    public TaskTracker getTaskTracker() {
        return taskTracker;
    }

    public void setTaskTracker(TaskTracker taskTracker) {
        this.taskTracker = taskTracker;
    }

    private boolean isTaskTrackerStarted() {
        return taskTracker.getConfig().getBoolean(TaskConfiguration.USCHEDULE_ENABLE,
            TaskConfiguration.DEFAULT_USCHEDULE_ENABLE);
    }

    public Scheduler getScheduler() {
        return scheduler;
    }

}
